/**
 *
 * Created by rsj217 on 14/10/12.
 */


$(document).ready(function(){

    var area_url = location.protocol + "//" +  location.host + "/api/area";
    getArea(area_url);


})


function genDistrict(data){


    $('#city').change(function(){
        var provinceId  = $('#province').find('option:selected').attr('data-id');
        var cityId = $(this).find('option:selected').attr('data-id');
        var cityArr = data[provinceId - 1]['city'];
        districtArr = []
        for (var i = 0; i < cityArr.length; i++){
            if (cityArr[i]['id'] == cityId){
                districtArr =  cityArr[i]['district'];
                break
            }
        }
        var html = ''
        for (var i = 0; i < districtArr.length; i++){
            html += '<option data-id="'+ districtArr[i]['id'] +'">' + districtArr[i]['district'] + '</option>';
        }
        $('#district').html(html);
    })




}

function genCity(data){

    $('#province').change(function(){
            provinceId = $(this).find('option:selected').attr('data-id');
            var cityArr = data[provinceId - 1]['city'];

            var html = '';
            for (var i = 0; i < cityArr.length; i++){
                html +=  '<option data-id="'+ cityArr[i]['id'] +'">' + cityArr[i]['city'] + '</option>';
            }
            $('#city').html(html);

            var dhtml = ''
            if ($.inArray(provinceId, [1, 4, 7, 28])){
                var districtArr = data[provinceId - 1]['city'][0]['district'];
                for (var i = 0; i < districtArr.length; i++){
                    dhtml += '<option data-id="'+ districtArr[i]['id'] +'">' + districtArr[i]['district'] + '</option>';
                }
                $('#district').html(dhtml);
            }
    })
}


function genProvince(data){

    if (data['reason'] == 'successed'){
        var provinceArr = data['result'];

        html = ''
        for (var i =0; i < provinceArr.length; i++){
            html +=  '<option data-id="'+ provinceArr[i]['id'] +'">' + provinceArr[i]['province'] + '</option>';
        }
        $('#province').html(html);

        disHtml = '';
        disArr = provinceArr[0]['city'][0]['district'];
        for (var i = 0; i < disArr.length; i++ ){
            disHtml +=  '<option data-id="'+ disArr[i]['id'] +'">' + disArr[i]['district'] + '</option>';
        }
        $("#district").html(disHtml);
        return provinceArr
    }
}


function getArea(area_url){
    $.ajax({
        async: true,
        url: area_url,
        type: 'get',
        dataType: 'json',
        success: function(data) {
            var provinceArr = genProvince(data);
            genCity(provinceArr);
            genDistrict(provinceArr);
        },
        //timeout:3000
        error: function(XMLHttpRequest, textStatus) {
            alert('请求数据失败，请重新刷新！')
        }
    });



}


